/**
 * 简化的多模型对比服务
 * 直接实现多模型对比功能，无需复杂的适配器层
 */

export interface SimpleModelConfig {
  name: string;
  apiKey: string;
  baseUrl: string;
  provider: string;
}

export interface SimpleComparisonResult {
  modelName: string;
  content: string;
  duration: number;
  tokenUsage?: {
    prompt: number;
    completion: number;
    total: number;
  };
  cost?: number;
  error?: string;
}

export class SimpleMultiModelService {
  private models: Map<string, SimpleModelConfig> = new Map();
  private modelConfigs: Map<string, any> = new Map(); // 存储从后端获取的模型配置
  private initialized: boolean = false;

  constructor() {
    this.initializeModels();
  }

  /**
   * 从后端API获取模型配置
   */
  private async initializeModels() {
    try {
      // 使用相对路径，让Vite代理转发到后端
      const response = await fetch('/api/v1/model-configs', {
        headers: {
          'Content-Type': 'application/json'
        }
      });
      if (response.ok) {
        const configs = await response.json();
        console.log('📦 从后端获取的模型配置:', configs);

        // 将后端配置转换为我们的格式
        console.log('🔄 处理后端模型配置，数量:', configs.length);
        configs.forEach((config: any, index: number) => {
          console.log(`📝 处理模型 ${index + 1}:`, config);

          // 检查模型是否激活且健康（healthy或warning）
          const isActive = config.isActive !== false;
          const isHealthy = config.status === 'healthy' || config.status === 'warning';
          const isAvailable = isActive && isHealthy;

          console.log(`🔍 模型 ${config.name || config.id} 状态检查:`, {
            isActive,
            status: config.status,
            isHealthy,
            isAvailable
          });

          if (config.id && isAvailable) {
            console.log(`✅ 添加在线模型: ${config.name || config.id} (状态: ${config.status})`);
            
            // 标准化配置字段名
            const standardizedConfig = {
              id: config.id,
              name: config.name,
              modelName: config.model_name || config.modelName,
              provider: config.provider,
              apiKey: config.api_key || config.apiKey,
              baseUrl: config.api_base || config.baseUrl || config.apiBase,
              status: config.status,
              enabled: config.enabled !== false
            };
            
            console.log(`📋 标准化后的配置:`, standardizedConfig);
            this.modelConfigs.set(config.id, standardizedConfig);
            
            this.addModel({
              name: standardizedConfig.name || standardizedConfig.id,
              apiKey: standardizedConfig.apiKey || 'backend-managed',
              baseUrl: standardizedConfig.baseUrl || '/api/v1',
              provider: standardizedConfig.provider || 'unknown'
            });
          } else {
            console.warn(`⚠️ 跳过离线或无效模型: ${config.name || config.id} (状态: ${config.status})`);
          }
        });
        console.log('✅ 模型配置处理完成，modelConfigs大小:', this.modelConfigs.size);
        
        this.initialized = true;
        console.log('模型初始化完成，可用模型:', Array.from(this.modelConfigs.keys()));
      } else {
        console.warn('无法获取模型配置，使用默认配置');
        this.initializeDefaultModels();
      }
    } catch (error) {
      console.error('获取模型配置失败:', error);
      this.initializeDefaultModels();
    }
  }

  /**
   * 备用的默认模型配置
   */
  private initializeDefaultModels() {
    console.log('使用默认模型配置');
    
    // 添加一些基本的模型配置作为备用，使用常见的模型ID
    const defaultModels = [
      { id: 'gpt-4', name: 'GPT-4', provider: 'openai' },
      { id: 'gpt-3.5-turbo', name: 'GPT-3.5-Turbo', provider: 'openai' },
      { id: 'claude-3-sonnet', name: 'Claude-3-Sonnet', provider: 'claude' },
      { id: 'deepseek-chat', name: 'DeepSeek Chat', provider: 'deepseek' },
      { id: 'qwen-max', name: 'Qwen Max', provider: 'qwen' }
    ];

    defaultModels.forEach(model => {
      // 添加到模型配置映射
      this.modelConfigs.set(model.id, {
        id: model.id,
        name: model.name,
        provider: model.provider,
        status: 'unknown',
        description: `${model.name} 模型`
      });
      
      // 添加到简单模型映射
      this.addModel({
        name: model.name,
        apiKey: 'backend-managed',
        baseUrl: '/api/v1',  // 使用相对路径
        provider: model.provider
      });
    });

    this.initialized = true;
    console.log('默认模型初始化完成，可用模型:', Array.from(this.modelConfigs.keys()));
  }

  /**
   * 等待初始化完成
   */
  private async ensureInitialized() {
    if (!this.initialized) {
      await this.initializeModels();
    }
  }

  addModel(config: SimpleModelConfig) {
    this.models.set(config.name, config);
  }

  async getAvailableModels(): Promise<string[]> {
    await this.ensureInitialized();
    // 优先返回从后端获取的模型ID
    if (this.modelConfigs.size > 0) {
      const models = Array.from(this.modelConfigs.keys());
      console.log('返回的可用模型列表:', models);
      return models;
    }
    const fallbackModels = Array.from(this.models.keys());
    console.log('使用备用模型列表:', fallbackModels);
    return fallbackModels;
  }

  /**
   * 获取模型信息
   */
  async getModelInfo(modelId: string): Promise<any> {
    await this.ensureInitialized();
    return this.modelConfigs.get(modelId) || null;
  }

  /**
   * 调用后端API生成内容
   */
  private async generateWithModel(
    modelName: string, 
    prompt: string, 
    hotItemId?: string, 
    platform?: string
  ): Promise<SimpleComparisonResult> {
    await this.ensureInitialized();
    const startTime = Date.now();

    try {
      // 查找模型配置，优先使用后端返回的模型ID
      let modelId = modelName;
      let modelConfig = null;
      
      // 尝试通过名称查找模型配置
      for (const [id, config] of this.modelConfigs.entries()) {
        if (config.name === modelName || config.id === modelName || id === modelName) {
          modelId = id;
          modelConfig = config;
          break;
        }
      }
      
      console.log(`使用模型ID: ${modelId}, 配置:`, modelConfig);

      // 验证模型配置
      if (!modelConfig) {
        throw new Error(`未找到模型 ${modelName} 的配置信息`);
      }
      
      // 如果API密钥被掩码或缺失，尝试从前端模型配置存储获取
      if (!modelConfig.apiKey || modelConfig.apiKey.includes('*') || modelConfig.apiKey === 'backend-managed') {
        console.log(`⚠️ 模型 ${modelName} 的API密钥被掩码，尝试从前端存储获取...`);
        
        // 尝试从localStorage获取模型配置
        try {
          const frontendConfigs = JSON.parse(localStorage.getItem('model-config-store') || '{}');
          const frontendConfig = frontendConfigs.state?.configs?.find((c: any) => 
            c.modelName === modelConfig.modelName || 
            c.id === modelId || 
            c.name === modelConfig.name
          );
          
          if (frontendConfig?.apiKey) {
            console.log(`✅ 从前端存储获取到API密钥`);
            modelConfig.apiKey = frontendConfig.apiKey;
            modelConfig.baseUrl = frontendConfig.baseUrl || modelConfig.baseUrl;
            modelConfig.provider = frontendConfig.provider || modelConfig.provider;
          }
        } catch (error) {
          console.warn('获取前端模型配置失败:', error);
        }
      }
      
      if (!modelConfig.apiKey || modelConfig.apiKey.includes('*')) {
        throw new Error(`模型 ${modelName} 缺少有效的API密钥配置`);
      }

      // 根据是否有热点ID决定使用哪个API端点
      let apiUrl: string;
      let requestBody: any;

      if (hotItemId && hotItemId !== 'general-content') {
        // 如果有具体的热点ID，使用热点内容生成API
        // 使用相对路径，让Vite代理转发到后端
        apiUrl = '/api/v1/hot-content/generate';
        requestBody = {
          hot_item_id: hotItemId,
        platform: platform || 'general',
        writing_angle: 'creative_writing',
        user_prompt: prompt,
          model_name: modelConfig?.modelName || modelId,
          temperature: 0.7,
          max_tokens: 2000,
          stream: false,
          provider: modelConfig?.provider,
          api_key: modelConfig?.apiKey,
          api_base: modelConfig?.baseUrl
        };
      } else {
        // 普通AI对话使用通用生成API
        // 使用相对路径，让Vite代理转发到后端
        apiUrl = '/ai/generate';
        requestBody = {
          model: modelConfig?.modelName || modelId,
          messages: [
            { role: 'user', content: prompt }
          ],
          parameters: {
        temperature: 0.7,
        max_tokens: 2000,
            top_p: 0.9,
            frequency_penalty: 0,
            presence_penalty: 0
          },
          stream: false,
          provider: modelConfig?.provider,
          api_key: modelConfig?.apiKey,
          api_base: modelConfig?.baseUrl
        };
      }

      console.log(`🚀 调用模型 ${modelId} 的API:`, {
        url: apiUrl,
        provider: requestBody.provider,
        hasApiKey: !!requestBody.api_key,
        apiBase: requestBody.api_base,
        modelName: requestBody.model || requestBody.model_name
      });

      const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      });

      if (!response.ok) {
        const errorText = await response.text();
        console.error(`❌ 模型 ${modelId} API调用失败:`, {
          status: response.status,
          statusText: response.statusText,
          errorText,
          requestBody
        });
        throw new Error(`API调用失败: ${response.status} - ${errorText}`);
      }

      const result = await response.json();
      const duration = Date.now() - startTime;

      console.log(`模型 ${modelName} 生成结果:`, result);

      // 根据使用的API端点处理不同的响应格式
      let content: string;
      let usage: any;

      if (hotItemId && hotItemId !== 'general-content') {
        // 热点内容生成API的响应格式
        content = result.content || result.data?.content || result.generated_content || result.text || '';
        usage = result.usage;
      } else {
        // 通用AI生成API的响应格式
        content = result.content || result.choices?.[0]?.message?.content || result.text || '';
        usage = result.usage;
      }

      return {
        modelName,
        content: content,
        duration,
        tokenUsage: usage ? {
          prompt: usage.prompt_tokens || 0,
          completion: usage.completion_tokens || 0,
          total: usage.total_tokens || 0
        } : {
          prompt: Math.ceil(prompt.length / 4),
          completion: Math.ceil(content.length / 4),
          total: Math.ceil(prompt.length / 4) + Math.ceil(content.length / 4)
        },
        cost: result.cost || this.calculateCost(
          usage?.total_tokens || Math.ceil(prompt.length / 4) + Math.ceil(content.length / 4),
          modelName
        )
      };

    } catch (error) {
      return {
        modelName,
        content: '',
        duration: Date.now() - startTime,
        error: error instanceof Error ? error.message : '生成失败'
      };
    }
  }

  /**
   * 计算API调用成本
   */
  private calculateCost(totalTokens: number, modelName: string): number {
    const costPer1k = modelName.toLowerCase().includes('gpt-4') ? 0.03 : 
                     modelName.toLowerCase().includes('claude') ? 0.015 : 0.002;
    return parseFloat(((totalTokens / 1000) * costPer1k).toFixed(4));
  }

  /**
   * 并行对比多个模型
   */
  async compareModels(
    prompt: string, 
    modelNames: string[], 
    maxConcurrency = 3,
    hotItemId?: string,
    platform?: string
  ): Promise<SimpleComparisonResult[]> {
    const results: SimpleComparisonResult[] = [];

    // 分批处理，避免过多并发
    for (let i = 0; i < modelNames.length; i += maxConcurrency) {
      const batch = modelNames.slice(i, i + maxConcurrency);
      const batchPromises = batch.map(modelName => 
        this.generateWithModel(modelName, prompt, hotItemId, platform)
      );

      const batchResults = await Promise.all(batchPromises);
      results.push(...batchResults);
    }

    return results;
  }

  /**
   * 获取模型统计信息
   */
  getModelStats(results: SimpleComparisonResult[]) {
    const successfulResults = results.filter(r => !r.error);
    
    if (successfulResults.length === 0) {
      return {
        totalModels: results.length,
        successfulModels: 0,
        averageResponseTime: 0,
        totalCost: 0,
        fastestModel: null,
        slowestModel: null
      };
    }

    const averageResponseTime = Math.round(
      successfulResults.reduce((sum, r) => sum + r.duration, 0) / successfulResults.length
    );

    const totalCost = successfulResults.reduce((sum, r) => sum + (r.cost || 0), 0);

    const fastestModel = successfulResults.reduce((fastest, current) => 
      current.duration < fastest.duration ? current : fastest
    );

    const slowestModel = successfulResults.reduce((slowest, current) => 
      current.duration > slowest.duration ? current : slowest
    );

    return {
      totalModels: results.length,
      successfulModels: successfulResults.length,
      averageResponseTime,
      totalCost: parseFloat(totalCost.toFixed(4)),
      fastestModel: fastestModel.modelName,
      slowestModel: slowestModel.modelName,
      successRate: ((successfulResults.length / results.length) * 100).toFixed(1)
    };
  }

  /**
   * 估算单次生成成本
   */
  estimateCost(prompt: string, modelName: string): number {
    const promptTokens = Math.ceil(prompt.length / 4);
    const estimatedCompletionTokens = Math.min(promptTokens * 1.5, 1000);
    const totalTokens = promptTokens + estimatedCompletionTokens;

    const costPer1k = modelName.includes('GPT-4') ? 0.03 : 
                     modelName.includes('Claude') ? 0.015 : 0.002;
    
    return parseFloat(((totalTokens / 1000) * costPer1k).toFixed(4));
  }
}

// 创建单例实例
export const simpleMultiModelService = new SimpleMultiModelService();
